package com.taskmanagement.service;

import com.taskmanagement.mapper.TaskMapper;
import com.taskmanagement.mapper.UserMapper;
import com.taskmanagement.entity.Task;
import com.taskmanagement.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

@Service
public class TaskService {

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private UserMapper userMapper;

    public List<Task> findByUserId(BigInteger userId) {
        return taskMapper.findByUserId(userId);
    }

    public Task findByIdAndUserId(BigInteger id, BigInteger userId) {
        return taskMapper.findByIdAndUserId(id, userId);
    }

    public Task createTask(Task task) {
        task.setStatus("NOT_STARTED");
        taskMapper.insert(task);
        return task;
    }

    public Task updateTask(Task task) {
        taskMapper.update(task);
        return task;
    }

    public boolean deleteTask(BigInteger id, BigInteger userId) {
        return taskMapper.delete(id, userId) > 0;
    }

    public boolean updateTaskStatus(BigInteger id, BigInteger userId, String status) {
        Task task = taskMapper.findByIdAndUserId(id, userId);
        if (task == null) {
            return false;
        }
        
        if ("COMPLETED".equals(status) && !"COMPLETED".equals(task.getStatus())) {
            task.setActualEndDate(new Date());
        }
        
        task.setStatus(status);
        return taskMapper.update(task) > 0;
    }

    /**
     * 根据用户名查找用户
     * @param username 用户名
     * @return 用户对象
     */
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

}
